package cn.edu.fzu.homemaking.chat.service.impl;

import cn.edu.fzu.homemaking.chat.cache.CompanyCache;
import cn.edu.fzu.homemaking.chat.cache.UserCache;
import cn.edu.fzu.homemaking.chat.domain.dto.MessageCountDto;
import cn.edu.fzu.homemaking.chat.domain.entity.Message;
import cn.edu.fzu.homemaking.chat.mapper.MessageMapper;
import cn.edu.fzu.homemaking.chat.service.MessageService;
import cn.edu.fzu.homemaking.common.SessionConstant;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MessageServiceImpl implements MessageService {

    @Resource
    private MessageMapper messageMapper;
    @Resource
    private UserCache     userCache;
    @Resource
    private CompanyCache  companyCache;

    @Override
    public List<Message> listReceive(Long userId, Long from, String userType) {
        return messageMapper.list(from, userId, null, getOrigin(userType));
    }


    @Override
    public int listReceiveCount(Long userId, String userType) {
        return messageMapper.count(null, userId, getOrigin(userType));
    }


    @Override
    public List<MessageCountDto> listUserCount(Long userId, String userType) {

        List<MessageCountDto> messageCountDtoList = messageMapper.listFromUserCount(userId, getOrigin(userType));
        for (MessageCountDto dto : messageCountDtoList) {
            if (SessionConstant.USER.equals(userType)) {
                dto.setFromName(companyCache.getNameById(dto.getFromId()));
            } else {
                dto.setFromName(userCache.getName(dto.getFromId(), SessionConstant.USER));
            }
        }
        return messageCountDtoList;
    }


    @Override
    public void add(Long from, Long to, String msg, Date createTime, boolean read, String origin) {
        messageMapper.insert(from, to, msg, createTime, read, origin);
    }


    @Override
    public void updateRead(Long fromId, Long toId, String userType) {
        List<Message> list = messageMapper.list(toId, fromId, false, getOrigin(userType));
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        List<Long> idList = new ArrayList<>(list.size());
        for (Message message : list) {
            idList.add(message.getId());
        }
        messageMapper.updateBatchRead(idList);
    }


    private String getOrigin(String userType) {
        if (SessionConstant.USER.equals(userType)) {
            //当前用户为顾客时，则查询出公司发送的消息
            userType = SessionConstant.COMPANY;
        } else {
            //当前用户为公司时，则查询出顾客发送的消息
            userType = SessionConstant.USER;
        }
        return userType;
    }
}
